<template>
  <el-dialog v-model="props.data.dialogStatus" draggable title="远程数据" width="80%" @close="handleRemoteCancel">
    <el-container>
      <el-tabs v-model="props.data.activeName" style="width: 100%">
        <el-tab-pane label="请求配置" name="config">
          <el-form :model="props.data.form" :rules="props.data.rules" label-width="auto" label-position="top">
            <el-form-item prop="url">
              <div style="display: flex; width: 100%">
                <el-input v-model="props.data.form.url" placeholder="请输入请求链接(http://或https://)">
                  <template #prepend>
                    <el-select v-model="props.data.form.method" style="width: 80px">
                      <el-option label="GET" value="get" />
                      <el-option label="POST" value="post" />
                    </el-select>
                  </template>
                </el-input>

                <el-button type="primary" @click="handleCodeEditEventRun" style="margin-left: 5px">运行</el-button>
              </div>
            </el-form-item>

            <el-form-item label="请求参数：">
              <el-tabs v-model="props.data.queryActiveName" style="width: 100%">
                <el-tab-pane label="Params" name="params">
                  <div class="little-bear-table-opt">
                    <el-table :data="props.data.form.params" size="small" border empty-text="空">
                      <el-table-column label="键名" align="center">
                        <template #default="{ row, $index }">
                          <el-input v-model="row.name" size="small" />
                        </template>
                      </el-table-column>
                      <el-table-column label="值" align="center">
                        <template #default="{ row, $index }">
                          <el-input v-model="row.value" size="small" />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center" width="60">
                        <template #default="{ row, $index }">
                          <el-button type="danger" icon="Delete" size="small" circle @click="handleRemoteFormDel('params', $index)" />
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="little-bear-table-opt-handle">
                      <el-button type="primary" link icon="CirclePlus" @click="handleRemoteFormAdd('params')"> 新增</el-button>
                    </div>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="Body" name="body">
                  <el-segmented v-model="props.data.form.body.type" :options="options" size="small" />

                  <div v-if="props.data.form.body.type == 'formdata'" class="little-bear-table-opt">
                    <el-table :data="props.data.form.body.formdata" size="small" border empty-text="空">
                      <el-table-column label="键名" align="center">
                        <template #default="{ row, $index }">
                          <el-input v-model="row.name" size="small" />
                        </template>
                      </el-table-column>
                      <el-table-column label="值" align="center">
                        <template #default="{ row, $index }">
                          <el-input v-model="row.value" size="small" />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center" width="60">
                        <template #default="{ row, $index }">
                          <el-button type="danger" icon="Delete" size="small" circle @click="handleRemoteFormDel('formdata', $index)" />
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="little-bear-table-opt-handle">
                      <el-button type="primary" link icon="CirclePlus" @click="handleRemoteFormAdd('formdata')"> 新增</el-button>
                    </div>
                  </div>

                  <code-edit v-else :codevalue="props.data.form.body.json" language="json" height="200px"></code-edit>
                </el-tab-pane>

                <el-tab-pane label="Cookie" name="cookie">
                  <div class="little-bear-table-opt">
                    <el-table :data="props.data.form.cookie" size="small" border empty-text="空">
                      <el-table-column label="键名" align="center">
                        <template #default="{ row, $index }">
                          <el-input v-model="row.name" size="small" />
                        </template>
                      </el-table-column>
                      <el-table-column label="值" align="center">
                        <template #default="{ row, $index }">
                          <el-input v-model="row.value" size="small" />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center" width="60">
                        <template #default="{ row, $index }">
                          <el-button type="danger" icon="Delete" size="small" circle @click="handleRemoteFormDel('cookie', $index)" />
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="little-bear-table-opt-handle">
                      <el-button type="primary" link icon="CirclePlus" @click="handleRemoteFormAdd('cookie')"> 新增</el-button>
                    </div>
                  </div>
                </el-tab-pane>

                <el-tab-pane label="Header" name="header">
                  <div class="little-bear-table-opt">
                    <el-table :data="props.data.form.header" size="small" border empty-text="空">
                      <el-table-column label="键名" align="center">
                        <template #default="{ row, $index }">
                          <el-input v-model="row.name" size="small" />
                        </template>
                      </el-table-column>
                      <el-table-column label="值" align="center">
                        <template #default="{ row, $index }">
                          <el-input v-model="row.value" size="small" />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center" width="60">
                        <template #default="{ row, $index }">
                          <el-button type="danger" icon="Delete" size="small" circle @click="handleRemoteFormDel('header', $index)" />
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="little-bear-table-opt-handle">
                      <el-button type="primary" link icon="CirclePlus" @click="handleRemoteFormAdd('header')"> 新增</el-button>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-form-item>

            <el-form-item label="返回响应：">
              <code-edit ref="remoteRespondCodeRef" :codevalue="props.data.respondCode" language="json" height="200px" :readonly="true"></code-edit>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="数据处理" name="datahandle">
          <div style="height: 500px">
            <code-edit v-show="props.data.successCodeStatus" ref="remoteSuccessCodeRef" @change="handleRemoteSuccessCodeChange"></code-edit>
          </div>
        </el-tab-pane>

        <el-tab-pane label="错误处理" name="errorhandle">
          <div style="height: 500px">
            <code-edit v-show="props.data.errorCodeStatus" ref="remoteErrorCodeRef" @change="handleRemoteErrorCodeChange"></code-edit>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-container>
    <template #footer>
      <div>
        <el-button @click="handleRemoteCancel">取消</el-button>
        <el-button type="primary" @click="handleRemoteSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { deepCopy, deepMerge, uuid, capitalizeFirstLetter } from '@/utils/index';

// 接受父组件传递的参数
const props = defineProps({
  data: {
    // 远程参数
    type: Object,
    default: {},
  },
});

const options = [
  {
    label: 'FormData',
    value: 'formdata',
  },
  {
    label: 'JSON',
    value: 'json',
  },
];

// 声明自定义事件
const emit = defineEmits(['save', 'cancel']);

// 远程成功处理代码ref
const remoteSuccessCodeRef = ref(null);

// 远程失败处理代码ref
const remoteErrorCodeRef = ref(null);

// 远程响应ref
const remoteRespondCodeRef = ref(null);

/**
 * 全程弹窗关闭
 */
const handleRemoteCancel = () => {
  props.data.form = {
    url: '', // 请求连接
    method: '', // 请求方式
    datatype: '', // 数据类型
    head: [], // 请求头
    query: [], // 请求参数
    body: [], // 请求数据
    successCode: '', // 成功处理代码
    errorCode: '', // 错误处理代码
  };
  props.data.dialogStatus = false;

  emit('cancel'); // 触发取消事件
};

/**
 * 保存
 */
const handleRemoteSave = () => {
  let data = deepCopy(props.data.form);

  // 触发保存事件
  emit('save', data);

  // 取消操作
  handleRemoteCancel();
};

/**
 * 选项数据新增
 */
const handleRemoteFormAdd = (sign) => {
  if (sign == 'formdata') {
    props.data.form.body[sign].push({ name: '', value: '' });
  } else {
    props.data.form[sign].push({ name: '', value: '' });
  }
};

/**
 * 选项数据删除
 */
const handleRemoteFormDel = (sign, index) => {
  // 直接删除指定索引项
  if (sign == 'formdata') {
    props.data.form.body[sign].splice(index, 1);
  } else {
    props.data.form[sign].splice(index, 1);
  }
};

/**
 * 成功处理代码改变
 */
const handleRemoteSuccessCodeChange = (codeValue) => {
  // 使用nextTick确保DOM更新后执行
  nextTick(() => {
    // 更新当前索引对应的自定义验证代码值
    props.data.form.successCode = codeValue;
  });
};

/**
 * 错误处理代码改变
 */
const handleRemoteErrorCodeChange = (codeValue) => {
  // 使用nextTick确保DOM更新后执行
  nextTick(() => {
    // 更新当前索引对应的自定义验证代码值
    props.data.form.errorCode = codeValue;
  });
};

const handleCodeEditEventRun = () => {
  let axiosConfig = {
    // `baseURL` 将自动加在 `url` 前面，除非 `url` 是一个绝对 URL。
    // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
    // baseURL: 'https://tongji.devjs.cn/api',

    // `url` 是用于请求的服务器 URL
    url: props.data.form.url ? props.data.form.url : 'https://tongji.devjs.cn/api/event',

    // `method` 是创建请求时使用的方法
    method: props.data.form.method,

    // 发送请求体数据
    data: {
      n: 'pageview',
      v: 3,
      u: 'https://www.axios-http.cn/docs/instance',
      d: 'axios-http.cn',
      r: 'https://www.baidu.com/',
    },

    withCredentials: false,
  };
  axios(axiosConfig)
    .then(function (response) {
      remoteRespondCodeRef.value.setEditorValue(JSON.stringify(response.data, null, 2));
    })
    .catch(function (error) {
      ElMessage({ message: error.message, type: 'error' });
    });
};

const getData = () => {
  return props.data;
};

watch(
  () => props.data.dialogStatus,
  (newVal, oldVal) => {
    if (newVal) {
      props.data.successCodeStatus = true;

      props.data.errorCodeStatus = true;

      nextTick(() => {
        remoteSuccessCodeRef.value.setEditorValue(props.data.form.successCode);

        remoteErrorCodeRef.value.setEditorValue(props.data.form.errorCode);
      });
    }
  },
  { deep: true },
);

defineExpose({
  getData,
});
</script>
